import React, { useState, useEffect } from 'react';
import { withRouter } from 'react-router-dom';
import { List, ListView, NavBar, Icon, Toast, Result } from 'antd-mobile';
import { R, ORDER_STATUSES } from "@/assets/js/dict"
import { GetHistoryOrders } from "@/api/tutor/orderList.js";
import nodata from "@/assets/svg/nodata.svg"

import star_selected from "@/assets/svg/star_selected.svg"
import star_unselected from "@/assets/svg/star_unselected.svg"

const Item = List.Item;
const Brief = Item.Brief;
const myImg = (src, key) => <img src={src} key={key} className="spe am-icon am-icon-md" alt="" />;

/**
 * 家教的历史订单列表
 * @param props
 * @returns {*}
 * @constructor
 */
function HistoryOrdersOfTutor (props) {

    let [userInfo] = useState(() => {
        let userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
        return userInfo
    });

    let [dataSource, setDataSource] = useState(new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2,
    }));

    let [orders, setOrders] = useState([]);

    //后台返回的分页数据
    let [records, setRecords] = useState({});

    let [word, setWord] = useState("加载中...");
    let [isLoading, setisLoading] = useState(true);


    function getOrders (pageNum, pageSize = 7) {
        GetHistoryOrders({ parent_id: userInfo.id, tutor_id: userInfo.id, pageNum: pageNum, pageSize: pageSize }).then(re => {
            console.log("re----> ", R.isSuccess(re));
            if (R.isSuccess(re)) {
                let data = R.getData(re);
                if (!!data.dataList && data.dataList.length > 0) {
                    setRecords(data);
                    orders.push(...data.dataList);
                    setOrders(orders);
                    let d = dataSource.cloneWithRows(orders);
                    setDataSource(d);
                    setisLoading(false);
                    if (data.pageIndex === data.totalPage) {
                        setWord("亲，没有更多了");
                    } else {
                        setWord("已加载");
                    }
                } else {
                    setWord("亲，没有更多了");
                }
            }
        }).catch(err => {
            console.error(err);
        });
    }

    //分数展示
    //todo 星星的颜色可能调整下，不同的评分，展示不一样的颜色
    function scoreShow (score) {
        let max = 5;
        let re = [];
        for (let i = 1; i <= score; i++) {
            re.push(myImg(star_selected, i));
        }
        for (let i = score + 1; i <= max; i++) {
            re.push(myImg(star_unselected, i))
        }
        return re;
    }


    useEffect(() => {
        getOrders(1, 5);
    }, []);

    //加载数据
    let onEndReached = (event) => {
        // load new data
        // hasMore: from backend data, indicates whether it is the last page, here is false
        if (isLoading || records.pageIndex === records.totalPage) {
            setWord("亲，没有更多了");
            return;
        } else {
            setisLoading(true);
            setWord("加载中...");
            getOrders(records.pageIndex + 1);
        }
    };

    const separator = (sectionID, rowID) => (
        <div
            key={`${sectionID}-${rowID}`}
            style={{
                backgroundColor: '#F5F5F9',
                height: 8,
                borderTop: '1px solid #ECECED',
                borderBottom: '1px solid #ECECED',
            }}
        />
    );

    const row = (rowData, sectionID, rowID) => {

        const isFinished = rowData.status === ORDER_STATUSES.FINISHED;

        /*
        * 服务正常结束的订单
        * */
        return (
            <div key={rowID + rowData.id} style={{ padding: '0 15px' }}>
                <Item key={rowData.id}
                    arrow="horizontal"
                    multipleLine
                    onClick={() => {
                        console.log("item-->", rowData);
                        sessionStorage.setItem("order_id", rowData.id);
                        props.history.push({
                            pathname: "/historyOrderDetailsOfTutor", state: {
                                order_id: rowData.id
                            }
                        });
                    }}
                    platform="cross"
                >
                    订单编号：{rowData.code}
                    <Brief> 辅导科目：{rowData.subjects}</Brief>
                    <Brief style={isFinished ? { color: 'green', fontWeight: 'bold' } : {
                        color: 'silver',
                        fontWeight: 'bold'
                    }}
                    > 状态：{rowData.status}</Brief>
                    <Brief> 中介费：¥{rowData.brokerage_fee ? rowData.brokerage_fee / 100 : 0}</Brief>
                    <Brief> 课时费：¥{rowData.class_fee ? rowData.class_fee / 100 : 0}</Brief>
                    <Brief style={isFinished ? {} : { display: 'none' }}> 评分：{scoreShow(rowData.finish_score)}</Brief>
                    <Brief style={isFinished ? {} : { display: 'none' }}> 评语：{rowData.finish_comment ? rowData.finish_comment : '未评价'}</Brief>
                    <Brief style={isFinished ? { display: 'none' } : {}}> 线下交流未果：{rowData.no_deal_comment}</Brief>
                    <Brief style={isFinished ? { display: 'none' } : {}}> 试讲失败说明：{rowData.unsatisfactory_comment}</Brief>
                    <Brief style={isFinished ? { display: 'none' } : {}}> 退款申请说明：{rowData.refund_comment}</Brief>
                    <Brief style={isFinished ? { display: 'none' } : {}}> 退款审核意见：{rowData.apply_refund_audit_comment}</Brief>
                    <Brief style={isFinished ? { display: 'none' } : {}}> 退款说明：{rowData.refund_comment}</Brief>
                    <Brief style={isFinished ? { display: 'none' } : {}}> 更新时间：{rowData.update_time}</Brief>
                    <Brief style={isFinished ? { display: 'none' } : {}}> 创建时间：{rowData.create_time}</Brief>
                </ Item>
            </div>
        )
    };

    if (orders.length === 0) {
        return (
            <div>
                <div className="page-title  home-tit">
                    <NavBar
                        mode="light"
                        icon={<Icon type="left" />}
                        onLeftClick={() => {
                            props.history.goBack()
                        }}
                    >
                        历史订单
                    </NavBar>
                </div>

                <div className="page-content  home-content">
                    <div className="publish-content-piece">
                        <div className="form-box">
                            <Result
                                buttonText={"返回主页"}
                                img={myImg(nodata, "none")}
                                title=""
                                message="暂无历史订单"
                                buttonType="primary"
                                onButtonClick={() => props.history.push("/mainTutor")}
                            />
                        </div>
                    </div>
                </div>
            </div>)
    } else {
        return (
            <div>
                <div className="page-title  home-tit" style={{ position: 'fixed', top: '0' }}>
                    <NavBar
                        mode="light"
                        icon={<Icon type="left" />}
                        onLeftClick={() => {
                            // props.history.goBack()
                            props.history.push({
                                pathname:'/mainTutor'
                            })
                        }}
                    >
                        历史订单
                    </NavBar>
                </div>

                <div className="page-content  home-content" style={{ top: '42px' }}>
                    <div className="publish-content-piece">
                        <ListView
                            dataSource={dataSource}
                            renderFooter={() => (<div style={{ padding: 30, textAlign: 'center' }}>
                                {word}
                            </div>)}
                            renderRow={row}
                            renderSeparator={separator}
                            className="am-list"
                            pageSize={4}
                            useBodyScroll
                            onScroll={() => {
                            }}
                            scrollRenderAheadDistance={500}
                            onEndReached={onEndReached}
                            onEndReachedThreshold={10}
                        />
                    </div>
                </div>
            </div>

        );
    }


}

export default withRouter(HistoryOrdersOfTutor);